<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-row>
          <el-button type="success" @click="handleCreate">&emsp;新增&emsp;</el-button>
          <el-button type="danger" @click="handleDeleteAll">批量删除</el-button>
          <el-form ref="listQuery" :inline="true" :model="listQuery" class="demo-form-inline">
            <el-form-item label="">
              <el-select v-model="listQuery.status" clearable filterable placeholder="徽章状态">
                <el-option
                  v-for="item in badgeStatus"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-select v-model="listQuery.type_id" clearable filterable placeholder="徽章类别">
                <el-option
                  v-for="item in badgeType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-input v-model="listQuery.keyword" clearable placeholder="请输入名称" type="text"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchSubmit">查询</el-button>
              <el-button type="primary" @click="resetSubmit">重置</el-button>
            </el-form-item>
          </el-form>
        </el-row>
      </div>
      <div v-loading="listLoading" class="item">
        <el-table ref="dataList" :data="menuList" :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                  border row-key="id" style="width:100%;margin-bottom: 20px;"
                  @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection"></el-table-column>
          <el-table-column label="序号" prop="id"></el-table-column>
          <el-table-column label="名称" prop="name"></el-table-column>
          <el-table-column label="头像" prop="picture">
            <template slot-scope="scope">
              <el-popover max-width="420" placement="right" trigger="hover">
                <img :src="scope.row.picture" alt="" style="max-width: 200px;max-height: 200px">
                <img slot="reference" :src="scope.row.picture" alt="" style="width: 50px;">
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="类别" prop="badge_type.name"></el-table-column>
          <el-table-column label="状态" prop="status">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status === 1" type="success">开启</el-tag>
              <el-tag v-if="scope.row.status === 2" type="danger">隐藏</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="排序" prop="sort"></el-table-column>
          <el-table-column label="操作" width="260px">
            <template slot-scope="scope">
              <el-button icon="el-icon-present" plain size="mini" type="warning" @click="handleGive(scope.row)">赠送
              </el-button>
              <el-button icon="el-icon-edit" plain size="mini" type="primary" @click="handleUpdate(scope.row)">编辑
              </el-button>
              <el-button icon="el-icon-delete" plain size="mini" type="danger" @click="handleDelete(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <cus-pagination
          :limit.sync="listQuery.perPage"
          :page.sync="listQuery.page"
          :total="total"
          @pagination="getList"
        />
      </div>
    </el-card>
    <!-- 删除弹框 -->
    <el-dialog
      :visible.sync="deleteDialogVisible"
      title="确定删除吗?"
      width="435px"
    >
      <span style=""><em style="font-style:normal;color:red">删除后不可恢复</em>，你还要继续吗？</span>
      <span slot="footer" class="dialog-footer">
            <el-button @click="deleteDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirmDelete">确 定</el-button>
        </span>
    </el-dialog>
    <!-- 新增编辑弹框 -->
    <el-dialog v-dialogDrag :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible"
               @close="handleCloseDialog('editRulesForm')"
    >
      <el-form ref="editRulesForm" :model="editRulesForm" :rules="editRulesFormRules" class="demo-ruleForm"
               label-width="120px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="editRulesForm.name" clearable placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="类别" prop="type_id">
          <el-select v-model="editRulesForm.type_id" filterable placeholder="徽章类别">
            <el-option
              v-for="item in badgeType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图片" prop="picture">
          <el-upload
            ref="uploadNode"
            :auto-upload="true"
            :file-list="editShowPicture"
            :http-request="customizeUpload"
            :limit="1"
            :on-change="handleChange"
            :on-error="handleError"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            action=""
            list-type="picture-card"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model.number="editRulesForm.sort" clearable placeholder="请输入排序数字"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="editRulesForm.status">
            <el-radio :label="1">显示</el-radio>
            <el-radio :label="2">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogFormVisible = false">返回</el-button>
          <el-button type="primary" @click="submitForm('editRulesForm')">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 赠送弹框 -->
    <el-dialog v-dialogDrag :visible.sync="giveFormVisible" title="赠送" @close="handleGiveCloseDialog">
      <el-form ref="giveForm" :model="giveForm" :rules="giveFormRules" class="demo-ruleForm" label-width="120px">
        <el-form-item label="名称">
          <el-input v-model="giveForm.name" disabled placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="类别">
          <el-select v-model="giveForm.badge_id" disabled filterable placeholder="徽章类别">
            <el-option
              v-for="item in badgeType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item disabled label="图片">
          <el-upload
            :auto-upload="true"
            :file-list="giveShowPicture"

            :http-request="customizeUpload"
            :limit="1"
            :on-change="handleChange"
            :on-error="handleError"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            action=""
            disabled
            list-type="picture-card"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户编号" prop="user_code">
          <el-input v-model.number="giveForm.user_code"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogFormVisible = false">返回</el-button>
          <el-button type="primary" @click="giveSubmit('giveForm')">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { deleteData, listData, listTypeData, postAddData, postGiveData, putEditData } from '@/api/badge/badgeList'

import { IMG_UPLOAD_URL } from '../../data/basic_data'

export default {
  data() {
    return {

      confirmBtn: false,

      giveShowPicture: [],
      giveFormRules: {
        user_code: [{ type: 'number', required: true, message: '请输入用户编号', trigger: 'blur' }]
      },
      giveForm: {
        name: undefined,
        picture: undefined,
        badge_id: undefined,
        user_code: undefined
      },
      giveFormVisible: false,
      // 图片展示数组
      editShowPicture: [],
      // upload节点
      uploadNode: '',
      // token值

      // 徽章类别
      badgeType: [],
      // 徽章状态
      badgeStatus: [
        { value: 1, label: '开启' },
        { value: 2, label: '隐藏' }
      ],
      // 要修改的当前行的idsearchSubmit
      row_id: 0,
      // 表单规则
      editRulesFormRules: {
        name: [{ required: true, message: '请输入名称1-30字符', trigger: 'blur', min: 1, max: 30 }],
        sort: [{ required: true, message: '请输入排序数字', trigger: 'blur' }, {
          type: 'number',
          min: 1,
          message: '请输入大于1的数值'
        }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
        type_id: [{ required: true, message: '请选择类别', trigger: 'change' }],
        picture: [{ required: true, message: '请选择图片', trigger: 'change' }]
      },
      editRulesForm: {
        name: undefined,
        type_id: undefined,
        picture: undefined,
        sort: undefined,
        status: 1
      },
      dialogStatus: '',
      // dialog的头部信息
      titleMap: {
        update: '编辑',
        create: '新增'
      },
      dialogFormVisible: false,
      deleteDialogVisible: false,
      listLoading: false,
      menuList: [],
      limitList: [],
      listQuery: {
        page: 1,
        perPage: 10,
        keyword: undefined,
        status: undefined,
        type_id: undefined
      },
      total: 0,
      // 勾选内容
      multipleSelection: [],
      // 要删除的内容的ids
      dataIds: ''
    }
  },
  created() {
    this.getTypeList()
    this.getList()
  },
  methods: {
    handleRelease(row) {
      this.row_id = row.id
      putRelease(this.row_id).then(response => {
        if (response.code === 200) {
          this.getList()
          this.dialogFormVisible = false
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          })
        } else {
          this.$message({
            message: response.message,
            type: 'error'
          })
        }
      })
    },
    getList() {
      this.listLoading = true
      let urlData = '?'
      if (this.listQuery.page) {
        urlData = urlData + `page=${this.listQuery.page}&`
      }
      if (this.listQuery.perPage) {
        urlData = urlData + `perPage=${this.listQuery.perPage}`
      }
      if (this.listQuery.status) {
        urlData = urlData + `&status=${this.listQuery.status}`
      }
      if (this.listQuery.type_id) {
        urlData = urlData + `&type_id=${this.listQuery.type_id}`
      }
      if (this.listQuery.keyword) {
        urlData = urlData + `&keyword=${this.listQuery.keyword}`
      }
      listData(urlData).then((response) => {
        this.menuList = response.data.list
        this.total = response.data.meta.total
        this.listLoading = false
        this.confirmBtn = false
      })
    },
    getTypeList() {
      let urlData = '?page=1&perPage=1000000'
      listTypeData(urlData).then(response => {
        response.data.list.forEach(item => {
          if (item.status === 1) {
            this.badgeType.push({ value: item.id, label: item.name })
          }
        })
      })
    },
    searchSubmit() {
      this.listQuery.page = 1
      this.getList()
    },
    resetSubmit() {
      this.listQuery.page = 1
      this.listQuery.perpage = 10
      this.listQuery.type_id = undefined
      this.listQuery.status = undefined
      this.listQuery.keyword = undefined
    },
    // 点击新增
    handleCreate() {
      this.$nextTick(() => {
        this.editShowPicture = []
        document.querySelector('.el-upload').style = 'display:block'
      })
      this.resetForm('editRulesForm')
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    // 图片批量上传
    handleRemove(file, fileList) {
      document.querySelector('.el-upload').style = 'display:block'
      this.editRulesForm.picture = ''
    },
    handleError() {
      document.querySelector('.el-upload').style = 'display:block'
      this.editRulesForm.picture = ''
    },
    handleChange() {
      document.querySelector('.el-upload').style = 'display:none'
    },
    handleSuccess() {
      this.editRulesForm.picture = this.ossLastImgUrl
    },
    // 点击编辑
    handleUpdate(row) {
      this.row_id = row.id
      this.editRulesForm.name = row.name
      this.editRulesForm.sort = row.sort
      this.editRulesForm.status = row.status
      this.editRulesForm.type_id = row.type_id
      this.editRulesForm.picture = row.picture
      this.editShowPicture.push({ url: row.picture })
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        document.querySelector('.el-upload').style = 'display:none'
      })
    },
    handleCloseDialog() {
      this.editShowPicture.length = 0
      this.editRulesForm.picture = ''
      if (this.$refs[formName]) {
        this.$refs[formName].clearValidate() // 清除整个表单的校验
      }
    },

    handleGiveCloseDialog() {
      this.giveShowPicture.length = 0
      this.giveForm.picture = ''
    },
    // 重置表单内容
    resetForm(formName) {
      this.$nextTick(() => {
        // this.$refs[formName].resetFields();
        if (this.$refs[formName] !== undefined) {
          this.$refs[formName].resetFields()
        }
        this.cityList = []
        this.editRulesForm = {
          name: undefined,
          sort: undefined,
          status: 1,
          type_id: undefined,
          picture: undefined
        }

      })
    },
    submitForm(formName) {
      if (this.confirmBtn) return

      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.confirmBtn = true
          if (this.dialogStatus === 'create') {
            postAddData(this.editRulesForm).then(response => {
              if (response.code === 200) {
                this.getList()
                this.dialogFormVisible = false
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                })
              } else {
                this.confirmBtn = false
              }
            })
          } else {
            putEditData(this.row_id, this.editRulesForm).then(response => {
              if (response.code === 200) {
                this.getList()
                this.dialogFormVisible = false
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                })
              } else {
                this.confirmBtn = false
              }
            })
          }
        } else {
          return false
        }
      })
    },
    handleGive(row) {
      this.giveFormVisible = true
      this.giveForm.name = row.name
      this.giveForm.picture = row.picture
      this.giveShowPicture.push({ url: row.picture })
      this.giveForm.badge_id = row.type_id
      this.giveForm.user_code = undefined
      this.$nextTick(() => {
        document.querySelector('.el-upload').style = 'display:none'
      })
    },
    giveSubmit(formName) {
      if (this.confirmBtn) return
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.confirmBtn = true
          let obj = {}
          obj.badge_id = this.giveForm.badge_id
          obj.user_code = this.giveForm.user_code
          postGiveData(obj).then(response => {
            if (response.code === 200) {
              // this.getList()
              this.giveFormVisible = false
              this.$notify({
                type: 'success',
                message: '操作成功',
                position: 'bottom-right',
                showClose: false,
                duration: 3000
              })
            } else {
              this.confirmBtn = false
            }
          })
        } else {
          return false
        }
      })
    },
    // 勾选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 点击单个删除
    handleDelete(row) {
      this.dataIds = { ids: `${row.id}` }
      this.deleteDialogVisible = true
    },
    // 点击批量删除
    handleDeleteAll() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: '请先勾选要删除的特殊房间',
          type: 'warning'
        })
        return
      } else if (this.multipleSelection.length !== 0) {
        let ids = ''
        for (let key in this.multipleSelection) {
          ids += `${this.multipleSelection[key].id},`
        }
        ids = ids.substring(0, ids.length - 1)
        this.dataIds = { ids: ids }
      }
      this.deleteDialogVisible = true
    },
    // 确定删除
    confirmDelete() {
      if (this.confirmBtn) return
      this.confirmBtn = true
      this.deleteDialogVisible = false
      deleteData(this.dataIds).then((response) => {
        if (response.code === 200) {
          this.getList()
          this.deleteDialogVisible = false
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          })
        } else {
          this.confirmBtn = false
        }
      })
    }
  }
}
</script>

<style scoped>
[v-cloak] {
  display : none;
}

.clearfix:before,
.clearfix:after {
  display : table;
  content : "";
}

.clearfix:after {
  clear : both
}

.box-card {
  width : 100%;
}

.demo-form-inline {
  float : right;
}

/deep/ .el-card__header {
  padding-bottom : 0;
}

/deep/ .el-upload-list__item {
  transition : none !important;

}

/* .avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
} */
</style>
